from django.shortcuts import render

# Create your views here.


#  url(r'^qq/authorization/$', views.QQAuthURLView.as_view()),
from rest_framework import status
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from oauth.exceptions import OAuthQQAPIError
from oauth.models import OAuthQQUser

from oauth.serializers import OAuthQQUserSerializer
from oauth.utils import OAuthQQ
from rest_framework_jwt.settings import api_settings



class QQAuthURLView(APIView):
    """
    获取QQ登录的url    ?next=xxx
    """
    def get(self,request):


        """获取next参数"""
        next = request.query_params.get('next')
        """拼接QQ登录的网址"""
        oauth = OAuthQQ(state=next)
        login_url = oauth.get_qq_login_url()

        return Response({'login_url':login_url})

class QQAuthUserView(CreateAPIView):
    """
    QQ用户登录
    """
    serializer_class = OAuthQQUserSerializer
    def get(self,request):
        # 获取code
        code = request.query_params.get('code')

        if not code:
            return Response({'message':'缺少code'},status=status.HTTP_400_BAD_REQUEST)
        # 凭借code获取access_token
        oauth_qq = OAuthQQ()
        try:
            # 凭借code获取access_token
            access_token = oauth_qq.get_access_token(code)
            # 凭借access_token  获取 openID
            openid = oauth_qq.get_openid(access_token)
        except OAuthQQAPIError:
            return Response({'message':'获取access_token失败'},status=status.HTTP_503_SERVICE_UNAVAILABLE)
        # 凭借openID查询 数据库OAthQQuser 判断用户是否存在
        try:
            oauth_qq_user = OAuthQQUser.objects.get(openid = openid)
        except OAuthQQUser.DoesNotExist:
            # 如果数据不存在,处理openid 并返回
            access_token = oauth_qq.generate_bind_user_access_token(openid)
            return Response({'access_token':access_token})

        else:
            # 如果数据存在，表示用户已经绑定过身份，签发jwt token
            # 如果数据存在，表示用户已经绑定过身份， 签发JWT token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            user = oauth_qq_user.user
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)


            return Response({
                'username':user.username,
                'user_id':user.id,
                'token':token,
            })
        # 根据open_ID查询数据库OAUTHQQUSE 判断用户是否存在
        # 如果数据存在,表示用户已经绑定过身份 ,签发 JWT token
        # 如果数据不存在,处理open_ID 并返回



    # def post(self,request):
    #     pass